/*
 * AddDictionaryDialog.java
 *
 * Created on Sobota, 2008, január 19, 15:21
 */
package eu.easyedu.dictionary.explorer;

import eu.easyedu.dictionary.api.model.Language;
import eu.easyedu.dictionary.api.resources.Bundle;
import eu.easyedu.dictionary.api.util.DatabaseUtils;
import eu.easyedu.dictionary.api.util.DerbyDriver;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLayeredPane;
import javax.swing.OverlayLayout;
import org.netbeans.api.db.explorer.ConnectionManager;
import org.netbeans.api.db.explorer.DatabaseConnection;

/**
 *
 * @author  hlavki
 */
public class AddDictionaryDialog extends javax.swing.JDialog {

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(AddDictionaryDialog.class.getName());
    private static final String URL_PREFIX = "jdbc:derby:";
    private static final String TEXT_PATTERN = "[-A-Za-z0-9 ]+";
    private static final String NUMBER_PATTERN = "[-()0-9 ]+";
    private Validator validator;
    private boolean prepared;

    /** Creates new form AddDictionaryDialog */
    public AddDictionaryDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        prepared = false;
        initComponents();
        addLayeredValidator();
        addValidations();
        setNetworkInfoEnabled();
        setDefaultLanguageEnabled();
        nameTextField.requestFocus();
        urlTextField.setText(getUrl(nameTextField.getText()));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serverTypeRadioGroup = new javax.swing.ButtonGroup();
        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        urlTextField = new javax.swing.JTextField();
        serverTypePanel = new javax.swing.JPanel();
        embeddedRadioButton = new javax.swing.JRadioButton();
        networkRadioButton = new javax.swing.JRadioButton();
        urlLabel = new javax.swing.JLabel();
        buttonPanel = new javax.swing.JPanel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        createDbCheckBox = new javax.swing.JCheckBox();
        hostTextField = new javax.swing.JTextField();
        hostLabel = new javax.swing.JLabel();
        portTextField = new javax.swing.JTextField();
        portLabel = new javax.swing.JLabel();
        defaultLanguagePanel = new javax.swing.JPanel();
        languageLabel = new javax.swing.JLabel();
        languageTextField = new javax.swing.JTextField();
        isoCodeLabel = new javax.swing.JLabel();
        isoCodeTextField = new javax.swing.JTextField();
        createDictionaryCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("addDictionaryDialog"); // NOI18N
        setResizable(false);

        nameLabel.setText(Bundle.getMessage("AddDictionaryDialog.nameLabel.text")); // NOI18N

        nameTextField.setName("nameTextField"); // NOI18N
        nameTextField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                textFieldCaretUpdate(evt);
            }
        });

        urlTextField.setEditable(false);
        urlTextField.setName("urlTextField"); // NOI18N

        serverTypePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(Bundle.getMessage("AddDictionaryDialog.serverTypePanel.border.title"))); // NOI18N
        serverTypePanel.setLayout(new java.awt.GridLayout(1, 0));

        serverTypeRadioGroup.add(embeddedRadioButton);
        embeddedRadioButton.setSelected(true);
        embeddedRadioButton.setText(Bundle.getMessage("AddDictionaryDialog.embeddedRadioButton.text")); // NOI18N
        embeddedRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionsChangeActionPerformed(evt);
            }
        });
        serverTypePanel.add(embeddedRadioButton);

        serverTypeRadioGroup.add(networkRadioButton);
        networkRadioButton.setText(Bundle.getMessage("AddDictionaryDialog.networkRadioButton.text")); // NOI18N
        networkRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionsChangeActionPerformed(evt);
            }
        });
        serverTypePanel.add(networkRadioButton);

        urlLabel.setText(Bundle.getMessage("AddDictionaryDialog.urlLabel.text")); // NOI18N

        saveButton.setText(Bundle.getMessage("AddDictionaryDialog.saveButton.text")); // NOI18N
        saveButton.setPreferredSize(new java.awt.Dimension(70, 24));
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(saveButton);

        cancelButton.setText(Bundle.getMessage("AddDictionaryDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(cancelButton);

        createDbCheckBox.setSelected(true);
        createDbCheckBox.setText(Bundle.getMessage("AddDictionaryDialog.createDbCheckBox.text")); // NOI18N
        createDbCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optionsChangeActionPerformed(evt);
            }
        });

        hostTextField.setText(null);
        hostTextField.setEnabled(false);
        hostTextField.setName("hostTextField"); // NOI18N
        hostTextField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                textFieldCaretUpdate(evt);
            }
        });

        hostLabel.setText(Bundle.getMessage("AddDictionaryDialog.hostLabel.text")); // NOI18N

        portTextField.setText(null);
        portTextField.setEnabled(false);
        portTextField.setName("portTextField"); // NOI18N
        portTextField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                textFieldCaretUpdate(evt);
            }
        });

        portLabel.setText(Bundle.getMessage("AddDictionaryDialog.portLabel.text")); // NOI18N

        defaultLanguagePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(Bundle.getMessage("AddDictionaryDialog.defaultLanguagePanel.border.title"))); // NOI18N

        languageLabel.setText(Bundle.getMessage("AddDictionaryDialog.languageLabel.text")); // NOI18N

        isoCodeLabel.setText(Bundle.getMessage("AddDictionaryDialog.isoCodeLabel.text")); // NOI18N

        javax.swing.GroupLayout defaultLanguagePanelLayout = new javax.swing.GroupLayout(defaultLanguagePanel);
        defaultLanguagePanel.setLayout(defaultLanguagePanelLayout);
        defaultLanguagePanelLayout.setHorizontalGroup(
            defaultLanguagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(defaultLanguagePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(languageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(languageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(isoCodeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(isoCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        defaultLanguagePanelLayout.setVerticalGroup(
            defaultLanguagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, defaultLanguagePanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(defaultLanguagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(languageLabel)
                    .addComponent(languageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(isoCodeLabel)
                    .addComponent(isoCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        createDictionaryCheckBox.setSelected(true);
        createDictionaryCheckBox.setText(Bundle.getMessage("AddDictionaryDialog.createDictionaryCheckBox.text")); // NOI18N
        createDictionaryCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createDictionaryCheckBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(buttonPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(nameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(urlLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(urlTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE))
                    .addComponent(serverTypePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(hostLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hostTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(portLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(portTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                    .addComponent(defaultLanguagePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(createDbCheckBox)
                        .addGap(18, 18, 18)
                        .addComponent(createDictionaryCheckBox)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(urlLabel)
                    .addComponent(urlTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hostLabel)
                    .addComponent(hostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portLabel)
                    .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(defaultLanguagePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createDbCheckBox)
                    .addComponent(createDictionaryCheckBox))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(serverTypePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-383)/2, (screenSize.height-333)/2, 383, 333);
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        validator.refreshValidation(this.getFocusOwner());
        log.info("validator count " + validator.invalidFieldsCount());
        if (validator.isCorrect()) {
            this.prepared = true;
            setVisible(false);

            //            try {
//                DatabaseConnection conn = DatabaseConnection.create(DatabaseUtils.getDefaultDriver(),
//                        urlTextField.getText(), "app", "APP", "app", true);
//                ConnectionManager.getDefault().addConnection(conn);
//                DictionaryService dictionaryService = ServiceFactory.getService(DictionaryService.class,
//                        DatabaseUtils.getConnection(conn.getName()));
//                dictionaryService.createDictionaryDDL();
//                WordBookService wordBookService = ServiceFactory.getService(WordBookService.class,
//                        DatabaseUtils.getConnection(conn.getName()));
//                Language lang = wordBookService.addLanguage(new Language(isoCodeTextField.getText(), languageTextField.getText()));
//                DictionaryList.getDefault().add(new Dictionary(nameTextField.getText(), lang, conn.getName()));
//                setVisible(false);
//            } catch (Exception ex) {
//                Exceptions.printStackTrace(ex);
//            }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void textFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_textFieldCaretUpdate
        urlTextField.setText(getUrl(nameTextField.getText()));
}//GEN-LAST:event_textFieldCaretUpdate

    private void optionsChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optionsChangeActionPerformed
        setNetworkInfoEnabled();
        urlTextField.setText(getUrl(nameTextField.getText()));
    }//GEN-LAST:event_optionsChangeActionPerformed

    private void createDictionaryCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createDictionaryCheckBoxActionPerformed
        setDefaultLanguageEnabled();
    }//GEN-LAST:event_createDictionaryCheckBoxActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JCheckBox createDbCheckBox;
    private javax.swing.JCheckBox createDictionaryCheckBox;
    private javax.swing.JPanel defaultLanguagePanel;
    private javax.swing.JRadioButton embeddedRadioButton;
    private javax.swing.JLabel hostLabel;
    private javax.swing.JTextField hostTextField;
    private javax.swing.JLabel isoCodeLabel;
    private javax.swing.JTextField isoCodeTextField;
    private javax.swing.JLabel languageLabel;
    private javax.swing.JTextField languageTextField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JRadioButton networkRadioButton;
    private javax.swing.JLabel portLabel;
    private javax.swing.JTextField portTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JPanel serverTypePanel;
    private javax.swing.ButtonGroup serverTypeRadioGroup;
    private javax.swing.JLabel urlLabel;
    private javax.swing.JTextField urlTextField;
    // End of variables declaration//GEN-END:variables

    protected String toDatabaseName(String name) {
        return name.toLowerCase().replace(' ', '-');
    }

    protected String getUrl(String name) {
        StringBuffer url = new StringBuffer(URL_PREFIX);
        if (networkRadioButton.isSelected()) {
            url.append("//").append(hostTextField.getText()).append(":");
            url.append(portTextField.getText()).append("/").append(toDatabaseName(name));
        } else if (embeddedRadioButton.isSelected()) {
            url.append(toDatabaseName(name));
        }
        if (createDbCheckBox.isSelected()) {
            url.append(";create=true");
        }
        return url.toString();
    }

    private final void setNetworkInfoEnabled() {
        hostTextField.setEnabled(networkRadioButton.isSelected());
        portTextField.setEnabled(networkRadioButton.isSelected());
    }

    private final void setDefaultLanguageEnabled() {
        languageTextField.setEnabled(createDictionaryCheckBox.isSelected());
        isoCodeTextField.setEnabled(createDictionaryCheckBox.isSelected());
    }

    private void addLayeredValidator() {
        validator = new Validator(this);
        JLayeredPane layeredPane = getRootPane().getLayeredPane();
        layeredPane.setLayout(new OverlayLayout(layeredPane));
        layeredPane.add(validator, (Integer) (JLayeredPane.DEFAULT_LAYER + 50));
        //validator.setBounds(0, 0, getWidth(), getHeight());
    }

    private void addValidations() {
        validator.addValidation(nameTextField, TEXT_PATTERN);
        validator.addValidation(languageTextField, TEXT_PATTERN);
        validator.addValidation(isoCodeTextField, TEXT_PATTERN);
        validator.addValidation(portTextField, NUMBER_PATTERN);
    }

    protected void setPrepared(boolean prepared) {
        this.prepared = prepared;
    }

    public boolean isPrepared() {
        return prepared;
    }

    public Language getLanguage() {
        return new Language(isoCodeTextField.getText(), languageTextField.getText());
    }

    public String getDictionaryName() {
        return nameTextField.getText();
    }

    public boolean createDictionary() {
        return createDictionaryCheckBox.isSelected();
    }

    public DerbyDriver getDerbyDriver() {
        return networkRadioButton.isSelected() ? DerbyDriver.NETWORK : DerbyDriver.EMBEDDED;
    }

    public String getUrl() {
        return urlTextField.getText();
    }
}
